package com.atguigu.flink.state;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/4/10
 *
 *   keyed state，都是在当前Task初始化时，从备份中获取状态。
 *
 *
 * 检测每种传感器的水位值，如果连续的两个水位值超过10，就输出报警。
 */
public class Demo4_KeyedValueState
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {
                       //声明变量存储上一个传感器的水位
                       private ValueState<Integer> lastVc;

                       //private int lastVc;

                       // keyed state，都是在当前Task初始化时，从备份中获取状态。
                       @Override
                       public void open(Configuration parameters) throws Exception {
                           lastVc = getRuntimeContext().getState(new ValueStateDescriptor<>("lastVc", Integer.class));
                       }

                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                           //当前是第一条数据，就没有上一个水位
                           Integer lastVcNum = lastVc.value();

                           if (lastVcNum != null && lastVcNum > 10 && value.getVc() > 10){
                               out.collect(value + "报警....");
                           }

                           //保存当前的水位到状态中，方便后续比较
                           lastVc.update(value.getVc());


                       }
                   })
                   .print();

                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
